package com.ltx.blog_ltx.controller;

import com.alibaba.fastjson.JSONObject;
import com.ltx.blog_ltx.entity.dto.UserDto;
import com.ltx.blog_ltx.entity.dto.Userinfo;
import com.ltx.blog_ltx.entity.pojo.Attention;
import com.ltx.blog_ltx.entity.pojo.Fans;
import com.ltx.blog_ltx.entity.pojo.User;
import com.ltx.blog_ltx.mapper.FansMapper;
import com.ltx.blog_ltx.mapper.UnreadNumMapper;
import com.ltx.blog_ltx.mapper.UserMapper;
import com.ltx.blog_ltx.mapper.attentionMapper;
import com.ltx.blog_ltx.until.FileUntil;
import com.ltx.blog_ltx.until.jwtUntil;
import com.sun.corba.se.spi.ior.ObjectKey;
import com.sun.imageio.plugins.jpeg.JPEG;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@RestController
public class UserController {

    @Autowired
    public UserMapper userMapper;
    @Autowired
    public FansMapper fansMapper;
    @Autowired
    public attentionMapper attentionMapper;
    @Autowired
    public UnreadNumMapper unreadNumMapper;

    @PostMapping("/login")
    public Map<String, String> login(@RequestBody JSONObject param){
        System.out.println("您进来了咯");
        UserDto user = new UserDto();
        String useremile = param.getString("useremile");
        String userName = userMapper.queryNameByEmile(useremile);
        if(userName==null){
            userName=userMapper.queryNameByPhone(useremile);
        }
        user.setUserName(userName);
        user.setUserPwd(param.getString("userPwd"));
        String pwd = userMapper.queryPwdByName(user.getUserName());
        if(pwd==null){
            HashMap<String, String> Map = new HashMap<>();
            Map.put("jieguo","该用户不存在");
            return Map;
        }else if(!pwd.equals(user.getUserPwd())){
            HashMap<String, String> Map = new HashMap<>();
            Map.put("jieguo","密码错误");
            return Map;
        }else {
            String userHead = userMapper.getUserHeadByName(user.getUserName());
            HashMap<String, String> Map = new HashMap<>();
            System.out.println(user.getUserName()+"----------------------");
            Map.put("user_Token",jwtUntil.createJwt(user.getUserName()));
            Map.put("userHead",userHead);
            Map.put("userName",userName);
            Map.put("fansNum", String.valueOf(userMapper.queryFansNum(userName)));
            Map.put("AttentionNum", String.valueOf(userMapper.queryAttentionNum(userName)));
            return Map;
        }
    }

    @PostMapping("/enroll")
    public Map<String,Object> enroll(@RequestBody JSONObject param){
        HashMap<String, Object> Map = new HashMap<>();
        String zhanghao2 = param.getString("zhanghao2");
        String password2_1 = param.getString("password2_1");
        String password2_2 = param.getString("password2_2");
        if(!password2_1.equals(password2_2)){
            Map.put("result","两次密码不一致");
            return Map;
        }
        Pattern pattern1 = Pattern.compile("[a-zA-Z0-9]+[\\.]{0,1}[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z]+");
        Pattern pattern2 = Pattern.compile("^[1]\\d{10}$");
        boolean matches1 = pattern1.matcher(zhanghao2).matches();
        boolean matches2 = pattern2.matcher(zhanghao2).matches();
        User user = new User();
        if(matches1){
            user.setUserPwd(password2_1);
            user.setUserId((int) ((Math.random() * 9 + 1) * 100000));
            user.setUserName("码上学习用户"+(int) ((Math.random() * 9 + 1) * 100000));
            user.setUserEmile(zhanghao2);
            user.setUserHead("http://47.115.224.29:5001/userimg/u=2393191727,861471760&fm=253&fmt=auto&app=138&f= JPEG.jpg\n");
            userMapper.enrollUserByEmile(user);
            Map.put("user_Token",jwtUntil.createJwt(user.getUserName()));
            Map.put("userName",user.getUserName());
        }else if(matches2){
            user.setUserPwd(password2_2);
            user.setUserId((int) ((Math.random() * 9 + 1) * 100000));
            user.setUserName("码上学习用户"+(int) ((Math.random() * 9 + 1) * 100000));
            user.setUserPhone(zhanghao2);
            user.setUserHead("http://47.115.224.29:5001/userimg/u=2393191727,861471760&fm=253&fmt=auto&app=138&f=JPEG.jpg\n");
            userMapper.enrollUserByPhone(user);
            Map.put("user_Token",jwtUntil.createJwt(user.getUserName()));
            Map.put("userName",user.getUserName());
        }else {
            Map.put("result","邮箱或者手机号格式有问题！！");
            return Map;
        }
        Map.put("result","ok!");
        return Map;
    }

    @PostMapping("/resetPassword")
    public String resetPassword(@RequestBody JSONObject param){
        String zhanghao = param.getString("zhanghao");
        String oldPassword = param.getString("oldPassword");
        String newPassword = param.getString("newPassword");
        Pattern pattern1 = Pattern.compile("[a-zA-Z0-9]+[\\.]{0,1}[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z]+");
        Pattern pattern2 = Pattern.compile("^[1]\\d{10}$");
        boolean matches1 = pattern1.matcher(zhanghao).matches();
        boolean matches2 = pattern2.matcher(zhanghao).matches();
        if(matches1){
            int isemile = userMapper.isemile(zhanghao);
            if(isemile>0){
                int i = userMapper.resetPasswordByEmile(zhanghao, oldPassword, newPassword);
                if(i>0){
                    return "修改密码成功";
                }else {
                    return "旧密码错误";
                }
            }else {
                return "用户邮箱不存在";
            }
        }else if(matches2){
            int isphone = userMapper.isphone(zhanghao);
            System.out.println(isphone);
            if(isphone>0){
                int i = userMapper.resetPasswordByPhone(zhanghao, oldPassword, newPassword);
                if(i>0){
                    return "修改密码成功";
                }else {
                    return "旧密码错误";
                }
            }else {
                return "用户手机号不存在";
            }
        }else {
            return "用户不存在";
        }
    }

    @PostMapping("/parseToken")
    public Map<String,Object> parse_token(@RequestBody JSONObject param){
        String user_token = param.getString("user_token");
        Map<String, Object> Map = new HashMap<>();
        Map.put("isExpire",jwtUntil.parse(user_token));
        String userName = jwtUntil.getTokenName(user_token);
        Map.put("fansNum", String.valueOf(userMapper.queryFansNum(userName)));
        Map.put("AttentionNum", String.valueOf(userMapper.queryAttentionNum(userName)));
        return Map;
    }


    @PostMapping("/uploadImge")
    public  String uploadImge(@RequestParam("file") MultipartFile file, @RequestParam("token")String token, HttpServletRequest request)
    {
        System.out.println("--------"+token+"---------");
        String tokenName = jwtUntil.getTokenName(token);
        //上传的绝对路径  /D:/note/userimg/
        String imgAbPath="/home/note/userimg/";
        String imgUrlDir="http:"+"//47.115.224.29:"+"5001/userimg/";
        //返回对应的File类型f
        File f = FileUntil.upload(file, imgAbPath);
        userMapper.updateImg(imgUrlDir+f.getName(),tokenName);        //更具用户名修改，用户头像的路径
        return imgUrlDir+f.getName();        //返回图片地址 http://localhost:5001/note/userimg/image-20200924014614792.png  注意图片名子中间有加密
    }
    @PostMapping("/getUserHead")
    public String getUserHead(@RequestBody JSONObject param){
        System.out.println("我进来了");
        String user_token = param.getString("user_token");
        String tokenName = jwtUntil.getTokenName(user_token);
        return userMapper.getUserHeadByName(tokenName);
    }

    @PostMapping("/BloggerInitialization")
    public User BloggerInitialization(@RequestBody JSONObject param){
        String userName = param.getString("userName");
        User user = userMapper.queryByName(userName);
        return user;
    }

    @PostMapping("/UserAttention")
    public int UserAttention(@RequestBody JSONObject param){
        String userdName = param.getString("userName");
        System.out.println(userdName+"==========================");
        String userToken = param.getString("userToken");
        String userName = jwtUntil.getTokenName(userToken);
        int userId = userMapper.queryIdByName(userName);  //当前用户
        int userdId = userMapper.queryIdByName(userdName);//被关注的用户
        int attentionId = (int) ((Math.random() * 9 + 1) * 100000);
        Attention attention = new Attention(attentionId, userId, userdId);
        unreadNumMapper.insertUnread(attentionId,userName,userdName);       //未读消息字段建立
        unreadNumMapper.insertUnread(attentionId+1,userdName,userName);       //未读消息字段建立
        attentionMapper.AttentionUser(attention);
        int fansId = (int) ((Math.random() * 9 + 1) * 100000);
        Fans fans = new Fans(fansId, userdId, userId);
        fansMapper.addFans(fans);
        userMapper.increaseAttentionNum(userId);
        userMapper.increaseFanNum(userdId);
        return userMapper.FansNum(userdId);
    }

    @PostMapping("/UserUnAttention")
    public int UserUnAttention(@RequestBody JSONObject param){
        String userdName = param.getString("userName");
        String userToken = param.getString("userToken");
        String userName = jwtUntil.getTokenName(userToken);
        int userId = userMapper.queryIdByName(userName);  //当前用户
        int userdId = userMapper.queryIdByName(userdName);//被关注的用户
        unreadNumMapper.deleteUnread(userName,userdName);
        unreadNumMapper.deleteUnread(userdName,userName);
        attentionMapper.deleteAttention(userId,userdId);
        fansMapper.musFans(userdId,userId);
        userMapper.musAttentionNum(userId);
        userMapper.musFanNum(userdId);
        return userMapper.FansNum(userdId);
    }

    @PostMapping("/isAttention")
    public boolean isAttention(@RequestBody JSONObject param){
        String userdName = param.getString("userName");
        String userToken = param.getString("userToken");
        String userName = jwtUntil.getTokenName(userToken);
        Integer userId = userMapper.queryIdByName(userName);  //当前用户
        Integer userdId = userMapper.queryIdByName(userdName);//被关注的用户
        Integer attention = attentionMapper.isAttention(userId, userdId);
        return (attention!=0);
    }

    @PostMapping("/queryInfo")
    public Userinfo queryInfo(@RequestBody JSONObject param){
        String userToken = param.getString("userToken");
        System.out.println(userToken);
        String userName = jwtUntil.getTokenName(userToken);
        Userinfo userinfo = userMapper.queryUserInfo(userName);
        return userinfo;
    }

    @PostMapping("/changeNote")
    public boolean changeNote(@RequestBody JSONObject param){
        String userName = param.getString("userName");
        String userNote = param.getString("userNote");
        return userMapper.changeNote(userName, userNote)==1;
    }

    @PostMapping("/getUserAttentionInfo")
    public List<Userinfo> GetUserAttentionInfo(@RequestBody JSONObject param){
        String userToken = param.getString("userToken");
        String userName = jwtUntil.getTokenName(userToken);
        int userId = userMapper.queryIdByName(userName);     //用户的id
        return userMapper.queryUserInfoList(userId);       //查询出用户关注的用户的信息并且返回到前端
    }

    @PostMapping("/userMap")
    public Map<String,Object> userMap(@RequestBody JSONObject param) {
        HashMap<String, Object> Map = new HashMap<>();
        String userToken = param.getString("userToken");
        String userName = jwtUntil.getTokenName(userToken);
        Map.put("userName",userName);
        String userPhone = userMapper.queryPhoneByName(userName);
        String userEmile = userMapper.queryEmileByName(userName);
        int sex = userMapper.querySexByName(userName);
        Date Birthday = userMapper.queryBirthdayByName(userName);
        Map.put("userPhone",userPhone);
        Map.put("userEmile",userEmile);
        Map.put("sex",sex);
        Map.put("Birthday",Birthday);
        return Map;
    }

    @PostMapping("/changeName")
    public String changeName(@RequestBody JSONObject param){
        String userToken = param.getString("userToken");
        String userName = jwtUntil.getTokenName(userToken);
        String newName = param.getString("userName");
        userMapper.changeName(userName,newName);
        return "ok!";
    }

    @PostMapping("/bindPhone")
    public String bindPhone(@RequestBody JSONObject param) {
        String userToken = param.getString("userToken");
        String userName = jwtUntil.getTokenName(userToken);
        String userPhone = param.getString("userPhone");
        userMapper.bindPhone(userName,userPhone);
        return "ok!";
    }

    @PostMapping("/bindEmile")
    public String bindEmile(@RequestBody JSONObject param) {
        String userToken = param.getString("userToken");
        String userName = jwtUntil.getTokenName(userToken);
        String userEmile = param.getString("userEmile");
        userMapper.bindEmile(userName,userEmile);
        return "ok!";
    }

    @PostMapping("/changeBirthday")
    public String changeBirthday(@RequestBody JSONObject param) {
        String userToken = param.getString("userToken");
        String userName = jwtUntil.getTokenName(userToken);
        Date userBirthday = param.getDate("userBirthday");
        userMapper.changeBirthday(userName,userBirthday);
        return "ok!";
    }
}
